//
//  RxTableViewCell.swift
//  RxSwiftExample
//
//  Created by LF on 2021/11/28.
//

import UIKit

class RxTableViewCell: UITableViewCell {
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        return label
    }()
    
    lazy var subLabel: UILabel = {
        let label = UILabel()
        return label
    }()
    
    var disposeBag: DisposeBag?
    
    var cellViewModel: RxCellViewModel? {
        didSet {
            if let viewModel = cellViewModel {
                bindCell(viewModel: viewModel)
            }
        }
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initSubViews()
        addConstraints()
        addRxSwift()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func initSubViews() {
        self.contentView.addSubview(titleLabel)
        self.contentView.addSubview(subLabel)
    }
    
    private func addConstraints() {
        
        titleLabel.snp.makeConstraints { make in
            make.leading.equalTo(self.contentView).offset(10)
            make.top.equalTo(self.contentView).offset(10)
        }
        
        subLabel.snp.makeConstraints { make in
            make.leading.equalTo(self.contentView).offset(10)
            make.top.equalTo(titleLabel.snp.bottom).offset(5)
        }
        
    }
    
    private func addRxSwift() {
        
    }
    
    
    override func prepareForReuse() {
        super.prepareForReuse()
        self.disposeBag = nil
    }
}

/// 数据绑定
extension RxTableViewCell {
    
    func bindCell(viewModel: RxCellViewModel) {
        
        let disposeBag = DisposeBag()
        
        viewModel
            .name
            .drive(self.titleLabel.rx.text)
            .disposed(by: disposeBag)
        
        viewModel
            .singer
            .drive(self.subLabel.rx.text)
            .disposed(by: disposeBag)
        
        self.disposeBag = disposeBag
    }
    
}
